package com.wetao.lib_common.view.graffiti;

import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.Path;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;

import com.wetao.lib_common.utils.LogUtils;

public class GraffitiPath {
    private GraffitiView mGraffitiView;
    private boolean mHasAdded;
    private final Path mPath = new Path(); // 画笔的路径
    private final Path mOriginPath = new Path();
    private RectF mBound = new RectF();
    private Rect mRect = new Rect();
    private final Matrix mTransform = new Matrix();
    private GraffitiPath(GraffitiView graffitiView) {
        mGraffitiView = graffitiView;
    }
    public static GraffitiPath toPath(GraffitiView graffitiView, Path p) {

        GraffitiPath path = new GraffitiPath(graffitiView);
        path.updatePath(p);

        return path;
    }

    public void updatePath(Path path) {
        mOriginPath.reset();
        this.mOriginPath.addPath(path);
        adjustPath(true);
    }

    public void onRemove() {
        mHasAdded = false;
    }

    public void onAdd() {
        mHasAdded = true;
    }

    public void refresh() {
        if (mHasAdded && mGraffitiView != null) {
            mGraffitiView.refresh();
        }
    }

    public GraffitiView getDoodle() {
        return mGraffitiView;
    }

    public void draw(Canvas canvas) {
        drawBefore(canvas);
        doDraw(canvas);
        drawAfter(canvas);
    }

    protected void doDraw(Canvas canvas) {
        canvas.drawPath(getPath(), mGraffitiView.getmPenPaint());
    }

    public Path getPath() {
        return mPath;
    }


    public void drawBefore(Canvas canvas) {

    }

    public void drawAfter(Canvas canvas) {

    }

    private void adjustPath(boolean changePivot) {
        resetLocationBounds(mRect);
        LogUtils.i("m3: adjustPath mRect left:" + mRect.left + ", top:" +  mRect.top +  ", right:" + mRect.right  +  ", bottom:" + mRect.bottom);
        mPath.reset();
        this.mPath.addPath(mOriginPath);
        /*mTransform.reset();
        mTransform.setTranslate(-mRect.left, -mRect.top);
        mPath.transform(mTransform);*/
        refresh();
    }

    private void resetLocationBounds(Rect rect) {
        if (mOriginPath == null) {
            return;
        }

        int diff = (int) (mGraffitiView.getSize() / 2 + 0.5f);
        mOriginPath.computeBounds(mBound, false);
        rect.set((int) (mBound.left - diff), (int) (mBound.top - diff), (int) (mBound.right + diff), (int) (mBound.bottom + diff));
    }
}
